import { defineStore } from 'pinia'
import axios from 'axios'

export const useScheduleStore = defineStore('schedule', {
  state: () => ({
    schedules: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchSchedules() {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get('/getAllArranges')
        this.schedules = response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch schedules'
        console.error('Error fetching schedules:', error)
      } finally {
        this.loading = false
      }
    },
    
    async fetchSchedulesByDoctor(dId) {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get(`/getArrangeByDoctor/${dId}`)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch doctor schedules'
        console.error('Error fetching doctor schedules:', error)
        return []
      } finally {
        this.loading = false
      }
    },
    
    async addSchedule(schedule) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/insertArrange', schedule)
        await this.fetchSchedules()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to add schedule'
        console.error('Error adding schedule:', error)
      } finally {
        this.loading = false
      }
    },
    
    async updateSchedule(schedule) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/updateArrange', schedule)
        await this.fetchSchedules()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to update schedule'
        console.error('Error updating schedule:', error)
      } finally {
        this.loading = false
      }
    },
    
    async deleteSchedule(arId) {
      this.loading = true
      this.error = null
      
      try {
        await axios.get(`/deleteArrange/${arId}`)
        await this.fetchSchedules()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to delete schedule'
        console.error('Error deleting schedule:', error)
      } finally {
        this.loading = false
      }
    }
  }
}) 